import os
import sys
import pandas as pd
import datetime
from MainConsolidator import MainConsolidator

class handler(object):
    @staticmethod
    def module_name():
        return 'Труба ТЭСЦ-1'
    @staticmethod
    def handle(row:pd.Series,consolidator:MainConsolidator)->pd.Series:
        product_up = None
        try:
            product = row["Первичный продукт"]
            vm_code = row['Вид материала в SAP ERP'][:4]
            pipe_type = consolidator.scalar_in_guid("Виды материалов ТЭСЦ-1",f"`Код`=='{vm_code}'","Тип трубы")
            if pipe_type=="НГП":
                strength_1 = consolidator.strength_by_steel(row["Марка стали <Производство>"])
                strength_steel = consolidator.strength_mapping(strength_1,row["Марка стали <Производство>"])
                gmsps = consolidator.get_gmsps(strength_steel[1],product)
                thickness = row["Толщина стенки, мм <Производство>"]
                diametr = row["Диаметр, мм <Производство>"]
                diametr_led = consolidator.nearest_in_guid("Параметры по Продукту ТЭСЦ-5",
                    f"`Производство`=='Труба нефтепроводная ТЭСЦ-5' and `Продукт`=='{product}'",
                    "Доп параметр1",
                    diametr,
                    "Доп параметр1")
                diametr_led_s = str(diametr_led).replace(".0","")
                print(f"product: {product}; gmsps: {gmsps}; thickness: {thickness}; diametr: {diametr}; diametr_led: {diametr_led_s}; ")
                thickness_range = None
                if "ГУ" in gmsps or "ГФ" in gmsps:
                    thickness_range = consolidator.scalar_in_guid("Параметры по Продукту ТЭСЦ-5",
                        f"`Производство`=='Труба нефтепроводная ТЭСЦ-5' and `Продукт`=='{product}' and `Доп параметр2` == 'ГУ' and `Мин`<={thickness}<=`Макс`","Диапазон")
                    product_up=f"{product}{diametr_led_s} {thickness_range} ГУ"
                else:
                    product_up=f"{product}{diametr_led_s} {gmsps}"
            
            print(f"{product} - pipe_type: {pipe_type} ({vm_code})")
            row["error"] = pd.NA
        except Exception as exp: 
            row["error"] = f"{exp}"
        finally:
            row["Продукт УП"]=product_up
            row["Время укрупнения"]=datetime.datetime.now()
            return row
        
    def debug_handle(self,inputDf:pd.DataFrame,consolidator:MainConsolidator,module:str=None)->pd.DataFrame:
        try:
            if module is None: return inputDf.apply(lambda row: self.handle(row,consolidator), axis=1)
            else: return inputDf[inputDf["Производство2"]==module].apply(lambda row: self.handle(row,consolidator), axis=1)
        except: raise
    
    def get_compiled(self):
        code:str=f"print('{__file__}')"
        try:
            with open(__file__,encoding="utf-8",mode="r") as f:
                code=f.read()
        except Exception as exp: 
            code=f"print('error: {exp}')"
        finally:
            cc = compile(code,"","exec")
            return cc

if __name__=="__pipe_t1__":
    consolidator:MainConsolidator
    record:pd.Series
    result:pd.Series
    result = handler.handle(record,consolidator)

